package main

import (
	"io"
	"net/http"
	"net/rpc"
	"net/rpc/jsonrpc"

	"gitee.com/lcc_dr/rpc/rpc_http/service"
)

/*
1、自定义一个函数
2、注册到rpc
3、rpc 启动

*/
var _ service.HelloService = (*HelloService)(nil)

type HelloService struct{}

func (h *HelloService) Hello(requests string, response *string) error {
	*response = "hello " + requests
	return nil
}

func (h *HelloService) Calc(res *service.Calc, response *int) error {
	*response = res.A * res.B
	return nil
}

func NewRpcWriteReadClosdHttp(w http.ResponseWriter, r *http.Request) *RpcWriteReadClose {

	return &RpcWriteReadClose{w, r.Body}
}

type RpcWriteReadClose struct {
	io.Writer
	io.ReadCloser
}

func main() {

	rpc.RegisterName(service.SERVICE_NAME, &HelloService{})

	rpc.HandleHTTP() //注册到rpc_http上，客户端只能可以通过rpc.http进行通信
	http.HandleFunc("/rpc_http", func(w http.ResponseWriter, r *http.Request) {

		conn := NewRpcWriteReadClosdHttp(w, r)
		rpc.ServeRequest(jsonrpc.NewServerCodec(conn)) //注册到http,可以通过http协议访问

	})
	http.ListenAndServe(":1234", nil)

}
